//
//  IpDetailController.m
//  Estate
//
//  Created by heyong on 2017/4/1.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "IpDetailController.h"

@interface IpDetailController ()

@end

@implementation IpDetailController

-(UITableView *)tableView{
    if(!_tableView){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [LSUtility setExtraCellLineHidde:_tableView tabHeader:NO tabFooter:NO];
        [_tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"ipCell"];
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(endEdit)];
        [_tableView addGestureRecognizer:tap];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.addIpModel=[[MultipleIPModel alloc]init];
    [self createView];
}

-(void)createView{
    UIView *topView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 64)];
    topView.backgroundColor=[UIColor colorWithRed:0.39 green:0.73 blue:0.65 alpha:1.00];
    [self.view addSubview:topView];
    
    UILabel *title=[[UILabel alloc]init];
    title.text=@"服务器配置";
    title.font=[UIFont systemFontOfSize:17.];
    title.textColor=[UIColor whiteColor];
    title.textAlignment=1;
    [topView addSubview:title];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(topView.mas_centerY).mas_offset(8);
        make.centerX.mas_equalTo(topView.mas_centerX);
        make.height.offset(50*BIZ);
        make.width.offset(300*BIZ);
    }];
    
    UIButton *backBtn=[[UIButton alloc]initWithFrame:CGRectMake(10, 25, 30, 30)];
    [backBtn setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal
     ];
    [backBtn addTarget:self action:@selector(backLoging) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    
    UIButton *saveBtn=[[UIButton alloc]init];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    saveBtn.titleLabel.font=[UIFont systemFontOfSize:14.];
    [saveBtn addTarget:self action:@selector(checkIp) forControlEvents:UIControlEventTouchUpInside];
    
    [topView addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(title.mas_centerY);
        make.right.offset(-3);
        make.height.offset(40);
        make.width.offset(60);
    }];
    
    [self.view addSubview:self.tableView];
    
}

#pragma mark -UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section=indexPath.section;
    QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"ipCell" forIndexPath:indexPath];
    if(section==0){
        if(self.ipModel){
            [cell configWithPlaceholder:@"" andValue:self.ipModel.ip andLabel:@"服务器地址:" andKeyType:UIKeyboardTypeASCIICapable];
            cell.textValueChangedBlock = ^(NSString *str) {
                self.ipModel.ip=str;
            };
        }else{
            [cell configWithPlaceholder:@"www.地址.com" andValue:self.addIpModel.ip andLabel:@"服务器地址:" andKeyType:UIKeyboardTypeNumbersAndPunctuation];
            cell.textValueChangedBlock = ^(NSString *str) {
                self.addIpModel.ip=str;
            };
        }
    }else if (section==1){
        if(self.ipModel){
            [cell configWithPlaceholder:@"可不填" andValue:self.ipModel.port andLabel:@"服务器端口:" andKeyType:UIKeyboardTypeNumberPad];
            cell.textValueChangedBlock = ^(NSString *str) {
                self.ipModel.port=str;
            };
        }else{
            [cell configWithPlaceholder:@"可不填" andValue:self.addIpModel.port andLabel:@"服务器端口:" andKeyType:UIKeyboardTypeNumberPad];
            cell.textValueChangedBlock = ^(NSString *str) {
                self.addIpModel.port=str;
            };
        }
        
    }else{
        
        cell.textField.tag=103;
        cell.textField.delegate=self;
        
        if(self.ipModel){
            [cell configWithPlaceholder:@"可不填" andValue:self.ipModel.remark andLabel:@"备注:" andKeyType:UIKeyboardTypeDefault];
            cell.textValueChangedBlock = ^(NSString *str) {
                self.ipModel.remark=str;
            };
        }else{
            [cell configWithPlaceholder:@"15字以内(可不填)" andValue:self.addIpModel.remark andLabel:@"备注:" andKeyType:UIKeyboardTypeDefault];
            cell.textValueChangedBlock = ^(NSString *str) {
                self.addIpModel.remark=str;
            };
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

#pragma mark -- 返回
-(void)backLoging{
    if(self.first){
        [LSUtility showToastWithMessage:@"您还未设置服务器信息，请先设置服务器信息！" inView:self.view Andtime:1.5];
        return;
    }else{
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }
}

#pragma mark -- 保存
-(void)checkIp{
    [LSHttpTool checkNetWork:^(NSString *status) {
        if([status isEqualToString:@"0"]){
            [LSUtility showToastWithMessage:@"请先连接网络！" inView:self.view Andtime:1.5];
        }else{
            
            if(self.ipModel||self.row){
                if([self.ipModel.ip isEqualToString:@""]||!self.ipModel.ip){
                    [LSUtility showToastWithMessage:@"您还未设置服务器信息，请先设置服务器信息！" inView:self.view Andtime:2];
                    return;
                }
                if(self.ipModel.remark.length>=15){
                    [LSUtility showToastWithMessage:@"备注最多15个字！" inView:self.view Andtime:2];
                    return;
                }
                
            } else{
                if([self.addIpModel.ip isEqualToString:@""]||!self.addIpModel.ip){
                    [LSUtility showToastWithMessage:@"您还未设置服务器信息，请先设置服务器信息！" inView:self.view Andtime:2];
                    return;
                }
                
                if(self.addIpModel.remark.length>=15){
                    [LSUtility showToastWithMessage:@"备注最多15个字！" inView:self.view Andtime:2];
                    return;
                }
            }
            /**
             * 接口校验
             */
            NSString *urlIp=@"";
            if(self.ipModel||self.row){
                if(!self.ipModel.port||[self.ipModel.port isEqualToString:@""]){
                    urlIp=[NSString stringWithFormat:@"http:%@/mobile/checkConn.do",self.ipModel.ip];
                }else{
                    urlIp=[NSString stringWithFormat:@"http:%@:%@/mobile/checkConn.do",self.ipModel.ip,self.ipModel.port];
                }
                
            }else{
                if(!self.addIpModel.port||[self.addIpModel.port isEqualToString:@""]){
                    urlIp=[NSString stringWithFormat:@"http:%@/mobile/checkConn.do",self.addIpModel.ip];
                }else{
                    urlIp=[NSString stringWithFormat:@"http:%@:%@/mobile/checkConn.do",self.addIpModel.ip,self.addIpModel.port];
                }
            }
            //去除url中的空格
            NSString *strUrl = [urlIp stringByReplacingOccurrencesOfString:@" " withString:@""];
            
            //服务器校验
            NSMutableDictionary *dic=[NSMutableDictionary dictionary];
            [LSUtility showMBProgress:self.view message:@"校验中,请稍等..."];
            [LSHttpTool PostCheckIP:strUrl parameters:dic success:^(id responseObject) {
                [LSUtility hideMBProgress:self.view];
                NSLog(@"responseObject:%@",responseObject);
                NSString *code=responseObject[@"code"];
                if([code isEqualToString:@"1"]){
                    
                    [self saveIP];
                    
                }else{
                    [LSUtility showToastWithMessage:@"保存失败，请确定您所填信息是否存在！" inView:self.view Andtime:2];
                }
            } failure:^(NSError *error) {
                [LSUtility hideMBProgress:self.view];
                [LSUtility showToastWithMessage:@"保存失败，请确定您所填信息是否存在！！" inView:self.view Andtime:2];
            }];
            
        }
    }];
}

-(void)saveIP{
    //保存 得到历史保存ip
    //反序列化
    NSData * data=DEF_PERSISTENT_GET_OBJECT(@"Multip");
    NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSMutableArray * dataData = [[NSMutableArray alloc]initWithArray:array];
    
    //判断是否存在ip重复 重复给出提示
    for (int i=0; i<dataData.count; i++) {
        MultipleIPModel *model=dataData[i];
        if(self.ipModel||self.row){
            if(self.row!=i){
                if([model.ip isEqualToString:self.ipModel.ip]&&[model.port isEqualToString:self.ipModel.port]){
                    [LSUtility showToastWithMessage:@"当前地址已存在,请重新输入！" inView:self.view Andtime:2];
                    return;
                }
            }
        }else{
            //没有端口
            if(!model.port&&!self.addIpModel.port){
                if([model.ip isEqualToString:self.addIpModel.ip]){
                    [LSUtility showToastWithMessage:@"当前地址已存在,请重新输入！" inView:self.view Andtime:2];
                    return;
                }
            }else{
                //有端口
                if([model.ip isEqualToString:self.addIpModel.ip]&&[model.port isEqualToString:self.addIpModel.port]){
                    [LSUtility showToastWithMessage:@"当前地址已存在,请重新输入！" inView:self.view Andtime:2];
                    return;
                }
            }
        }
    }
    //选中状态清空
    for (int i=0; i<dataData.count; i++) {
        MultipleIPModel *model=dataData[i];
        model.isSel=0;
        //更新数据
        [dataData replaceObjectAtIndex:i withObject:model];
    }
    
    //修改ip数据
    if(self.ipModel||self.row){
        //修改指定行数据
        MultipleIPModel *upModel=dataData[self.row];
        self.ipModel.isSel=1;
        upModel=self.ipModel;
        //更新数据
        [dataData replaceObjectAtIndex:self.row withObject:upModel];
        
    }
    //新增ip数据
    else{
        self.addIpModel.isSel=YES;
        [dataData addObject:self.addIpModel];
    }
    
    //存储新的ip源
    //序列化
    NSData * saveData = [NSKeyedArchiver archivedDataWithRootObject:dataData];
    DEF_PERSISTENT_SET_OBJECT(saveData,@"Multip");
    
    //存储当前ip
    if(self.ipModel||self.row){
        NSString *IP=@"";
        if(!self.ipModel.port||[self.ipModel.port isEqualToString:@""]){
            IP=self.ipModel.ip;
        }else{
            IP=[NSString stringWithFormat:@"%@:%@",self.ipModel.ip,self.ipModel.port];
        }
        //去除url中的空格
        NSString *strUrl = [IP stringByReplacingOccurrencesOfString:@" " withString:@""];
        DEF_PERSISTENT_SET_OBJECT(strUrl, @"SAVEIP");
        
    }else{
        NSString *IP=@"";
        
        if(!self.addIpModel.port||[self.addIpModel.port isEqualToString:@""]){
            IP=self.addIpModel.ip;
        }else{
            IP=[NSString stringWithFormat:@"%@:%@",self.addIpModel.ip,self.addIpModel.port];
        }
        //去除url中的空格
        
        NSString *strUrl = [IP stringByReplacingOccurrencesOfString:@" " withString:@""];
        DEF_PERSISTENT_SET_OBJECT(strUrl, @"SAVEIP");
    }
    //跳转
    if(self.first){
        LoginViewController *loginCtr=[[LoginViewController alloc]init];
        [self presentViewController:loginCtr animated:YES completion:^{
            
        }];
    }else{
        [self dismissToRootViewController];
    }
}

-(void)dismissToRootViewController
{
    UIViewController *vc = self;
    while (vc.presentingViewController) {
        vc = vc.presentingViewController;
        //登录页面存在 最底层设置为登录
        if([vc isKindOfClass:NSClassFromString(@"LoginViewController")]&& vc != nil){
            break;
        }
    }
    
    [vc dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark scrollview
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

-(void)endEdit{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
